package com.spdg.ring.offline;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import org.apache.http.util.CharArrayBuffer;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;
import cn.wolf.tools.Log;
import cn.wolf.tools.SdCardTool;
import cn.wolf.tools.StreamUtil;
import cn.wolf.tools.StringUtil;

import com.spdg.ring.common.Config;
import com.spdg.ring.common.Key;
import com.spdg.ring.entity.ContentEntity;
import com.spdg.ring.sqlite.model.Article;
import com.spdg.ring.sqlite.model.ArticleList;
import com.spdg.ring.sqlite.model.Menu;
import com.spdg.ring.sqlite.service.ArticleListService;
import com.spdg.ring.sqlite.service.ArticleService;
import com.spdg.ring.xml.ContentParser;

public class OfflineZipUitl {

	public static void parseZip(String zipDir, String zipName) {
		String zipPath = zipDir + zipName;
		if (StringUtil.isEmpty(zipPath))
			return;

		Log.d("parse zipfile, path is " + zipPath);

		File file = new File(zipPath);
		if (!file.exists()) {
			Log.d("file noexists. filepath is " + zipPath);
			return;
		}

		try {
			ZipFile zip = new ZipFile(file);
			for (Enumeration<?> entries = zip.entries(); entries.hasMoreElements();) {
				ZipEntry entry = ((ZipEntry) entries.nextElement());
				if (!entry.isDirectory()) {
					copyto(zip, entry);
				}
			}

		} catch (ZipException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void copyto(ZipFile zip, ZipEntry entry) {

		try {
			String filePath = entry.getName();
			String dirName = filePath.substring(0, filePath.indexOf("/"));
			String fileName = filePath.substring(filePath.indexOf("/") + 1, filePath.length());
			if (Config.OFFLINE_RING_PIC.equals(dirName)) {
				savepic(zip.getInputStream(entry), fileName);
			} else if (Config.OFFLINE_RING_LIST.equals(dirName)) {
				saveArticleList(zip.getInputStream(entry), fileName);
			} else if (Config.OFFLINE_RING_PAGE.equals(dirName)) {
				saveArticlePae(zip.getInputStream(entry), fileName);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void savepic(InputStream in, String fileName) {
		SdCardTool.write(in, Config.SDCARD_ARTICLE_PIC, fileName);
	}

	private static void saveArticlePae(InputStream in, String fileName) {
		SdCardTool.write(in, Config.SDCARD_OFFLINE_ARTICLE_PAGE_TEMP, fileName);
	}

	private static void saveArticleList(InputStream in, String fileName) {
		SdCardTool.write(in, Config.SDCARD_OFFLINE_ARTICLE_LIST_TEMP, fileName);
	}

	// =======================================
	// 把离线数据解析，存储到数据库
	// =======================================
	public static void save2sqlite(Context context, Menu menu) {
		if (menu != null && context != null) {
			String fileName = menu.getFile();
			if (!StringUtil.isEmpty(fileName)) {
				saveArticleList(context, fileName, fileName);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private static void saveArticleList(Context context, String parentFile, String fileName) {
		if (!StringUtil.isEmpty(fileName)) {
			if (fileName.contains(".")) {
				Log.d("filename:" + fileName);
				fileName = fileName.substring(0, fileName.indexOf("."));
			}

			File file = new File(Config.SDCARD_OFFLINE_ARTICLE_LIST_TEMP + fileName);
			if (file.exists()) {
				ContentParser parse = new ContentParser();

				List<ContentEntity> list = (List<ContentEntity>) parse.parse(file);

				if (list == null || list.isEmpty())
					return;

				List<ArticleList> articles = list.get(0).getItemList();

				if (articles == null)
					return;
				for (ArticleList article : articles) {
					saveArticleList(context, parentFile, article);
				}

				file.delete();
			}
		}
	}

	private static void saveArticleList(Context context, String parentFile, ArticleList article) {
		if (article != null) {
			String type = article.getType();

			ArticleListService service = ArticleListService.newInstance(context);

			article.setParentFile(parentFile);
			service.saveOrUpdate(article);

			if (Key.K_CONTENT_TYPE_ITEM.equals(type)) {
				saveArticlePage(context, article, article.getFile());
			} else {
				saveArticleList(context, article.getFile(), article.getFile());
			}
		}
	}

	private static void saveArticlePage(Context context, ArticleList articleList, String fileName) {
		File file = new File(Config.SDCARD_OFFLINE_ARTICLE_PAGE_TEMP + fileName);
		if (file != null && file.exists()) {
			Reader reader = null;
			FileInputStream in = null;
			String content = "";
			try {
				in = new FileInputStream(file);
				reader = new InputStreamReader(in, "UTF-8");
				CharArrayBuffer buffer = new CharArrayBuffer(0);
				char[] tmp = new char[1024];
				int l;
				while ((l = reader.read(tmp)) != -1) {
					buffer.append(tmp, 0, l);
				}

				content = buffer.toString();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				StreamUtil.closeSilently(reader);
			}

			if (!StringUtil.isEmpty(content)) {
				Article article = new Article();
				String articleContent = parseImgSrc(content);
				article.setContent(articleContent);
				article.setTitle(articleList.getName()); // 标题
				article.setDate(articleList.getDate()); // 日期
				article.setFile(fileName);
				ArticleService.newInstance(context).saveOrUpdate(article);
			}

			file.delete();
		}
	}

	/**
	 * 修改详细文章的img.src路径
	 * @param content
	 * @return
	 */
	private static String parseImgSrc(String content) {
		if (!StringUtil.isEmpty(content)) {
			Document doc = Jsoup.parse(content);
			Elements elements = doc.select("img");
			for (Element element : elements) {
				String srcKey = element.attr("alt");
				String imgSrc = "file://" + Config.SDCARD_ARTICLE_PIC + srcKey;
				element.attr("src", imgSrc);
			}
			
			Elements ems = doc.select("a");
			for (Element e : ems) {
				String srcKey = e.attr("target");
				if (!StringUtil.isEmpty(srcKey)) {
					String hrefStr = e.attr("href");
					e.attr("href", "newtab:" + hrefStr);
				}
			}

			return doc.toString();
		}

		return "";
	}

}
